package com.otoe.dilidilivid.view.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.otoe.dilidilivid.data.entity.ChoseItem;
import com.otoe.dilidilivid.R;
import com.otoe.dilidilivid.data.dao.VideoDao;
import com.otoe.dilidilivid.data.entity.VideoInfo;
import com.otoe.dilidilivid.adapter.ChoseTagAdapter;
import com.otoe.dilidilivid.utils.PathToUri;
import com.otoe.dilidilivid.data.operation.vidupload.Config;
import com.otoe.dilidilivid.data.operation.vidupload.UploadActivity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.view.View.GONE;

public class VideoUploadActivity extends AppCompatActivity {

    static final int REQUEST_VIDEO_CAPTURE = 1;
    static final int REQUEST_VIDEO = 2;
    private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
    //private HashSet mNameSet;
    private List<ChoseItem> mTagList;
    private RecyclerView mRecyclerView;
    private TextView mPublishBtn;
    private TextView tagsList;
    private TextView selectVideoBtn;
    private TextView useCameraBtn;
    private ChoseTagAdapter mAdapter;
    private SurfaceView mSurfaceView;
    private MediaPlayer mMediaPlayer;
    private LinearLayout selectVideoBar;
    private LinearLayout vedioPreviewBar;
    private Uri fileUri; // file url to store image/video

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //API24以上系统分享支持file:///开头
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_upload);

        //初始化标签下拉多选菜单
        initData();
        initView();
        //设定菜单展开缩小监听
        tagsList=findViewById(R.id.tag_select_btn);
        tagsList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mRecyclerView.getVisibility()==GONE) {
                    tagsList.setCompoundDrawablesWithIntrinsicBounds(getDrawable(R.drawable.down_arrow), null, null, null);
                    mRecyclerView.setVisibility(View.VISIBLE);
                }else{
                    tagsList.setCompoundDrawablesWithIntrinsicBounds(getDrawable(R.drawable.right_arrow), null, null, null);
                    mRecyclerView.setVisibility(GONE);
                }
            }
        });

        //初始化选取视频菜单
        selectVideoBar = findViewById(R.id.lv_select_videos);
        vedioPreviewBar = findViewById(R.id.video_preview_bar);
        mMediaPlayer = new MediaPlayer();
        mSurfaceView=(SurfaceView) findViewById(R.id.surCam);
        //打开摄像头
        findViewById(R.id.btnCam).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakeVideoIntent();
            }
        });
        //打开系统视频文件夹
        findViewById(R.id.btnStorage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_VIDEO);
            }
        });

        //各种按钮监听
        findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.delete_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 是否需要删除视频缓存？
                vedioPreviewBar.setVisibility(GONE);
                selectVideoBar.setVisibility(View.VISIBLE);
            }
        });
        findViewById(R.id.play_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {// 预览视频播放、暂停
                if(mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    findViewById(R.id.play_btn).setForeground(getDrawable(R.drawable.play_circle));
                }else{
                    mMediaPlayer.start();
                    findViewById(R.id.play_btn).setForeground(getDrawable(R.drawable.pause_circle));
                }
            }
        });
        String VideoTitle=((EditText) findViewById(R.id.ed_title)).getText().toString();
        findViewById(R.id.publish_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(fileUri==null){
                    sendToast("您还未选择要上传的视频",Toast.LENGTH_SHORT);
                    return;
                }
                Intent i = new Intent(getApplicationContext(), UploadActivity.class);
                String truePath = PathToUri.getPathFromUri(VideoUploadActivity.this,fileUri);
                i.putExtra("filePath", truePath);
                i.putExtra("isImage", false);
                String temp[]=truePath.split("/");
                String videoUrl="http://123.57.214.240/AndroidFileUpload/uploads/"+temp[temp.length-1];
                String img=videoUrl.replace("mp4","jpg");
                VideoInfo videoInfo=new VideoInfo();
                videoInfo.setTitle("video");
                videoInfo.setVideoUrl(videoUrl);
                videoInfo.setImg(img);
                videoInfo.setPlayNums(0);
                videoInfo.setDuration("4:10");
                videoInfo.setUname("小凯");
                new Thread(){
                    @Override
                    public void run(){
                        VideoDao videoDao=new VideoDao();
                        videoDao.insertVideo(videoInfo);
                    }
                }.start();
                startActivity(i);
            }
        });

        //录制视频上传
        findViewById(R.id.btnCam).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

                fileUri = getOutputMediaFileUri();

                // set video quality
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
                // name

                // start the video capture Intent
                startActivityForResult(intent, REQUEST_VIDEO);
            }
        });
    }

    /**
     * Creating file uri to store image/video
     */
    public Uri getOutputMediaFileUri() {
        return Uri.fromFile(getOutputMediaFile());
    }

    /**
     * returning image / video
     */
    private static File getOutputMediaFile() {

        // External sdcard location
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),
                Config.IMAGE_DIRECTORY_NAME);

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("vid", "Oops! Failed create "
                        + Config.IMAGE_DIRECTORY_NAME + " directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator);
        return mediaFile;
    }

    //初始化tag列表
    private void initData() {
        //mNameSet = new HashSet<>();
        mTagList = new ArrayList<>();
        String[] tags = { "动漫", "动物", "风景", "美食", "游戏", "爱情", "网红", "明星","科技","直播"};
        for (int i = 0; i < tags.length; i++) {
            ChoseItem item = new ChoseItem();
            item.setName(tags[i]);
            item.setChose(false);
            mTagList.add(item);
        }
    }

    private void initView() {

        mRecyclerView = findViewById(R.id.tag_chose_list);
        mPublishBtn = findViewById(R.id.publish_btn);
        GridLayoutManager manager = new GridLayoutManager(this, 5);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new ChoseTagAdapter(mTagList);
        mRecyclerView.setAdapter(mAdapter);
        mPublishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            //TODO 接受tags列表传回的信息

//                MainActivity.startActivity(ChoseTagActivity.this);
//                Gson gson = new Gson();
//                String gsonStr = gson.toJson(mNameSet);
//                SharedPreferencesUtil.putData("prefer", gsonStr);
//                Log.d(TAG, gsonStr);
            }
        });
    }

    //处理eventbus
    //@Subscribe(threadMode = ThreadMode.MAIN)

//    public void handleMessage(ChoseEvent event) {
//
//        mNameSet = event.getNameSet();
//
//    }


    //初始化播放器
    private void initPlayer(Uri uri) {
        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                play(uri);
            }
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }

    //调用摄像头
    private void dispatchTakeVideoIntent() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == RESULT_OK) {
            //显示视频
            selectVideoBar.setVisibility(GONE);
            vedioPreviewBar.setVisibility(View.VISIBLE);
            if (requestCode == REQUEST_VIDEO_CAPTURE) {
                Uri videoUri = intent.getData();
                //videoView.setVideoURI(videoUri);
                Log.e("视频uri",videoUri.toString());
                initPlayer(videoUri);
            }
            //打开视频文件后返回
            if (requestCode == REQUEST_VIDEO) {
                fileUri=intent.getData();
                Log.e("视频uri",fileUri.toString());
                //videoView.setVideoURI(uri);

                initPlayer(fileUri);
            }
        }
    }
    //播放视频
    public void play(Uri uri){
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            //设置需要播放的视频
            mMediaPlayer.setDataSource(getApplicationContext(),uri);
            //把视频画面输出到SurfaceView
            mMediaPlayer.setDisplay(mSurfaceView.getHolder());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            //获取视频时长
            int duration = mMediaPlayer.getDuration();
            Log.e("视频时长",""+duration);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    void sendToast(String str, int showTime)
    {
        Toast toast = Toast.makeText(this, str, showTime);
        toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL , 0, 0);  //设置显示位置
        TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
        toast.show();
    }
}